package com.lap.framework.junit.infra;

import com.lap.framework.junit.domain.FileInfo;
import com.lap.framework.junit.domain.repository.FileWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.util.CollectionUtils;

@Slf4j
public class FileWriteImpl implements FileWriter {

  private static final Charset UTF_8 = StandardCharsets.UTF_8;

  @Override
  public void write(List<FileInfo> list) {
    if (CollectionUtils.isEmpty(list)) {
      log.warn("生成代码文件为空");
      return;
    }
    list.forEach(
        file -> {
          try {
            String fileName = file.fileName();
            String filePath = file.path();

            File outputFile;
            if (filePath == null || filePath.trim().isEmpty()) {
              outputFile = new File(fileName);
            } else {
              outputFile = new File(filePath, fileName);
            }

            String content = file.content() == null ? "" : file.content();
            FileUtils.write(outputFile, content, UTF_8);
          } catch (IOException e) {
            log.error("写入文件失败: {} | 原因: {}", file.fileName(), e.getMessage(), e);
          }
        });
  }
}
